package com.learn.common.util;

import com.learn.common.exception.FormValidException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class FormValidateUtil{

    /**
     * 校验参数抛出异常
     * @param result
     * @throws Exception
     */
    public static StringBuffer validateForm(BindingResult result) throws BindException{
        List<FieldError> errors =  result.getFieldErrors();
        StringBuffer strb = null;
        if(errors != null && errors.size() > 0){
            strb = new StringBuffer("");
            for(FieldError error : errors){
                strb.append(error.getDefaultMessage());
                strb.append("\r\n");
            }
            throw new FormValidException(result);
        }
        return strb;
    }

    /**
     * 验证错误信息并返回一个Map映射关系，用于异步
     * @param result 绑定的结果集，封装的验证信息
     * @return
     */
    public static Map<String, String> validateMap(BindingResult result){
        Map<String, String> m = new HashMap<String, String>();
        if(result.hasErrors()){
            List<FieldError> errors = result.getFieldErrors();
            if(errors != null && errors.size() > 0){
                for(FieldError err: errors){
                    m.put(err.getField()+"Error", err.getDefaultMessage());
                }
            }
            return m;
        }
        return null;
    }
}